<?php

namespace App\Api\Controllers;

use App\Models\Commodity;
use App\Models\UserLog;
use Illuminate\Http\Request;
use App\Models\User;

class ElectricityFeeController extends Controller
{
    // public function store(Request $request){
    // 	$money = $request->input('money');
    //     $user = $this->user();
    //     //$date = date("Y-m-01",strtotime('-1 month'));
    //     //获取上个月电费
    //     //$electricityFee = UserLog::where(['currency_type'=>'electricity_fee','status'=>0])->whereDate('created_at','>',$date)->sum('out');
    //     if($electricityFee){
    //         //if($user->electricity_fee<$electricityFee){
    //         if($user->balance<$electricityFee){
    //             return $this->error('余额不足，请及时充值');
    //         }
    //         $r = (new UserLog())->change(-$electricityFee,$user->id,'balance','15','充值电费');
    //         $u = User::where('id',$user->id)->first()->toArray();
    //         $e = $u['electricity_fee']+$electricityFee;
    //         User::where('id',$user->id)->update(['electricity_fee'=>$e]);
    //         if($r){
    //             UserLog::where(['currency_type'=>'electricity_fee','status'=>0])->whereDate('created_at','>',$date)->update(['status'=>1]);
    //         }
    //     }
    //     return $this->success('充值成功');
    // }
    
     public function store(Request $request){
    	$money = $request->input('money');
        $user = $this->user();
        
        if($user->balance<$money){
            return $this->error('余额不足，请及时充值');
        }
        // if($user->electricity_fee+$money>0){
        // 	$eleFee = -($user->electricity_fee+$money);
        // }else{
        	$eleFee = $user->electricity_fee+$money;
       // }
        $r = (new UserLog())->change(-$money,$user->id,'balance','15','充值电费');
        // $u = User::where('id',$user->id)->first()->toArray();
        // $e = $u['electricity_fee']+$money;
        User::where('id',$user->id)->update(['electricity_fee'=>$eleFee]);
        if($r){
            UserLog::where(['currency_type'=>'electricity_fee','status'=>0])->update(['status'=>1]);
        }
        (new UserLog())->change($eleFee,$user->id,'electricity_fee','20','当前电费');
        return $this->success('充值成功');
    }
}
